#传递实参

#位置实参：实参的顺序与形参的顺序一致
def describe_pet(animal_type, pet_name = 'willie'):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

#关键字实参：关键字实参是传递给函数的名称-值对
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

#默认值：编写函数时，可给每个形参指定默认值。在调用函数中给形参提供了实参时，Python将使用指定的实参值；否则，将使用形参的默认值。
describe_pet(animal_type='dog')

#等效的函数调用
describe_pet('dog', 'willie')
describe_pet(animal_type='dog', pet_name='willie')
describe_pet('dog')


#返回值
#返回简单值
def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)

#让实参变成可选的
def get_formatted_name(first_name, last_name, middle_name=''):
    """返回整洁的姓名"""
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)

#返回字典
def build_person(first_name, last_name, age=''):
    """返回一个字典，其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)


#练习
#8-6
def city_country(city, country):
    """返回一个字符串，其中包含城市和国家"""
    city_country = city +',' + country
    return city_country.title()

city = city_country('santiago', 'chile')
print(city)

#8-7
def make_album(artist, album, number_of_songs=''):
    """返回一个字典，其中包含专辑的信息"""
    album = {'artist': artist, 'album': album}
    if number_of_songs:
        album['number_of_songs'] = number_of_songs
    return album

album = make_album('metallica', 'ride the lightning')
print(album)

album = make_album('metallica', 'master of puppets', number_of_songs=10)
print(album)

#传递列表
def greet_users(names):
    """向列表中的每位用户发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)


#在函数中修改列表
def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计，直到没有未打印的设计为止
    打印每个设计后，都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model: " + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

#禁止函数修改列表:向函数传递列表的副本而不是原件
#切片表示法[:]创建列表的副本
# function_name(list_name[:])

#练习
#8-9
def show_magicians(magicians):
    """打印魔术师名单"""
    for magician in magicians:
        print(magician.title())

magicians = ['harry houdini', 'david copperfield', 'criss angel']
show_magicians(magicians)

#8-10
def make_great(magicians):
    """在魔术师名单中添加字样“the great”"""
    great_magicians = []    
    while magicians:
        magician = magicians.pop()
        great_magician = magician +' the great'
        great_magicians.append(great_magician)
    for great_magician in great_magicians:
        magicians.append(great_magician)

# make_great(magicians)
# show_magicians(magicians)

#8-11
make_great(magicians[:])
show_magicians(magicians)
print('------------')
make_great(magicians)
show_magicians(magicians)

#传递任意数量的实参
#形参名*toppings中的星号让Python创建一个名为toppings的空元组，并将收到的所有值都封装到这个元组中
def make_pizza(*toppings):
    """概述要制作的比萨"""
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#结合使用位置实参和任意数量实参
#如果要让函数接受不同类型的实参，必须在函数定义中将接纳任意数量实参的形参放在最后
def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

#使用任意数量的关键字实参
#形参**user_info中的两个星号让Python创建一个名为user_info的空字典，并将收到的所有名称-值对都封装到这个字典中
def build_profile(first, last, **user_info):
    """创建一个字典，其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

#练习
#8-12
def make_sandwich(*toppings):
    """概述要制作的三明治"""
    print("\nMaking a sandwich with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_sandwich('pepperoni')
make_sandwich('mushrooms', 'green peppers', 'extra cheese')

#8-13
build_profile('albert', 'einstein', location='princeton', field='physics', age=27, hobby='reading')
#8-14
def make_car(manufacturer, model, **car_info):
    """创建一个字典，其中包含我们知道的有关汽车的一切"""
    car = {}
    car['manufacturer'] = manufacturer
    car['model'] = model
    for key, value in car_info.items():
        car[key] = value
    return car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

#将函数存储在模块中
#导入整个模块,通用示例：
# import module_name
# module_name.function_name()

#导入特定的函数,通用示例：
# from module_name import function_name
# function_name()
#导入任意数量的函数,通用示例：
# from module_name import function_0, function_1, function_2
# function_0()
# function_1()
# function_2()

#使用as给函数指定别名,通用示例：
# from module_name import function_name as fn
# fn()

#使用as给模块指定别名,通用示例：
# import module_name as mn
# mn.function_name()

#导入模块中的所有函数,通用示例：
# from module_name import *
# function_name()

#函数编写指南
#应给函数指定描述性名称，且只在其中使用小写字母和下划线
#每个函数都应包含简要地阐述其功能的注释，该注释应紧跟在函数定义后面，并采用文档字符串格式
#给形参指定默认值时，等号两边不要有空格：
# def function_name(parameter_0, parameter_1='default value')
#对于函数调用中的关键字实参，也应遵循这种约定：
# function_name(value_0, parameter_1='value')

#所有的import语句都应放在文件开头，唯一例外的情形是，在文件开头使用了注释来描述整个程序

